package com.openNetty.server.main;

import org.jboss.resteasy.plugins.server.embedded.SecurityDomain;
import org.jboss.resteasy.plugins.server.netty.NettyJaxrsServer;
import org.jboss.resteasy.spi.ResteasyDeployment;

import static com.openNetty.common.bean.MainContents.STARTPORT;

/**
 *  NETTY结合resteasy配置类
 *  此类为预留配置，如果需要对节点进行操作可配置此类
 *  开启此类即为默认开启httpweb server，可接受GET或POST请求
 *  具体方式请查看JBOSS的RESTEASY文档
 *
 * @author zhenggm
 * @create 2017-08-21 下午 1:17
 */
public class NettyContainer {


    private static final int port = Integer.parseInt(Global.properties.getProperty(STARTPORT));

    public static NettyJaxrsServer netty;

    public static ResteasyDeployment start() throws Exception {
        return start("");
    }

    public static ResteasyDeployment start(String bindPath) throws Exception {
        return start(bindPath, null);
    }

    /**
     * 加载resteasy调度
     * @param deployment
     * @throws Exception
     */
    public static void start(ResteasyDeployment deployment) throws Exception {
        netty = new NettyJaxrsServer();
        netty.setDeployment(deployment);
        netty.setPort(port);
        netty.setRootResourcePath("");
        netty.setSecurityDomain(null);
        netty.start();
    }

    /**
     * 域名端口绑定
     *
     * @param bindPath
     * @param domain
     * @return
     * @throws Exception
     */
    public static ResteasyDeployment start(String bindPath, SecurityDomain domain) throws Exception {
        ResteasyDeployment deployment = new ResteasyDeployment();
        deployment.setSecurityEnabled(true);
        return start(bindPath, domain, deployment);
    }

    public static ResteasyDeployment start(String bindPath, SecurityDomain domain,
                                           ResteasyDeployment deployment) throws Exception {
        netty = new NettyJaxrsServer();
        netty.setDeployment(deployment);
        netty.setPort(port);
        netty.setRootResourcePath(bindPath);
        netty.setSecurityDomain(domain);
        netty.start();
        return netty.getDeployment();
    }

    public static void stop() throws Exception {
        if (netty != null) {
            try {
                netty.stop();
            } catch (Exception e) {

            }
        }
        netty = null;
    }

}
